package org.oims.simpleserver.controllers.api.v1;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.oims.simpleserver.entities.db.FriendMsgItem;
import org.oims.simpleserver.entities.db.User;
import org.oims.simpleserver.entities.results.SimpleResult;
import org.oims.simpleserver.services.UserService;
import org.oims.simpleserver.utils.ReturnResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping(value = {"/api/v1"})
public class MessageController {
    private UserService userService;

    @GetMapping(value = {"/lst-friend-msg"})
    public SimpleResult getLatestFriendMessage(String friendMpNo, Integer msgNum, HttpSession session, HttpServletResponse resp){
        try {
            if(msgNum == null || msgNum < 0){
                msgNum = 200;
            }
            User user = (User) session.getAttribute("user");
            String userMpNo = user.getMpNo();
            List<FriendMsgItem> list = userService.getLstFriendMsgsAndUpdateStatus(userMpNo, friendMpNo, msgNum);

//            List<FriendMsgItem> list = userService.getLstFriendMsgsAndUpdateStatus("+86-17513289887", friendMpNo, msgNum);

            return ReturnResultUtil.getDataResult(list);
        }catch (Exception e){
            e.printStackTrace();
            resp.setStatus(500);
            return ReturnResultUtil.getServerErrorResult();
        }
    }

    @PostMapping(value = {"/friend-msg"})
    public SimpleResult sendFriendMsg(@RequestBody String params, HttpSession session, HttpServletResponse resp){
        try {
            JSONObject json = JSON.parseObject(params);
            String friendMpNo = json.getString("friendMpNo");
            int type = json.getIntValue("type");
            String content = json.getString("content");
            User user = (User) session.getAttribute("user");
            FriendMsgItem friendMsg = userService.sendMsgToFriend(user.getMpNo(), friendMpNo, type, content);

//            FriendMsgItem friendMsg = userService.sendMsgToFriend("+86-17513289887", friendMpNo, type, content);

            return ReturnResultUtil.getDataResult(friendMsg);
        }catch (Exception e){
            e.printStackTrace();
            resp.setStatus(500);
            return ReturnResultUtil.getServerErrorResult();
        }
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
